package com.zzz.email.util;

import java.security.SecureRandom;
import java.util.Random;

/**
 * 验证码生成工具类
 */
public class VerificationCodeUtil {
    
    private static final String CHARACTERS = "0123456789";
    private static final Random RANDOM = new SecureRandom();
    
    /**
     * 生成数字验证码
     * 
     * @param length 验证码长度
     * @return 生成的验证码
     */
    public static String generateNumericCode(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("验证码长度必须大于0");
        }
        
        StringBuilder code = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            code.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
        }
        return code.toString();
    }
    
    /**
     * 生成默认6位数字验证码
     * 
     * @return 生成的验证码
     */
    public static String generateNumericCode() {
        return generateNumericCode(6);
    }
    
    /**
     * 生成字母数字混合验证码
     * 
     * @param length 验证码长度
     * @return 生成的验证码
     */
    public static String generateAlphanumericCode(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("验证码长度必须大于0");
        }
        
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder code = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            code.append(characters.charAt(RANDOM.nextInt(characters.length())));
        }
        return code.toString();
    }
    
    /**
     * 验证验证码格式是否正确
     * 
     * @param code 验证码
     * @param length 期望的验证码长度
     * @return 是否格式正确
     */
    public static boolean isValidCode(String code, int length) {
        if (code == null || code.length() != length) {
            return false;
        }
        return code.matches("\\d{" + length + "}");
    }
}